<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

/**
 * 公用类
 */
class CommonController extends Controller
{
    public $request = null;
    public function __construct()
    {
        $this->request = request();
    }


    /**
     * 返回api设置
     */
    public  function returnApi($code, $msg, $type = false, $data = null)
    {
        $result = ['code' => $code, 'msg'  => $msg];
        if ($type) $result['content'] = $data;
        return $result;
    }

    /**
     * 处理分页数据，返回必要字段即可
     */
    public function disPageData($data)
    {
        $datas = [];
        $datas['data'] = $data['data'];
        $datas['total'] = $data['total'];
        $datas['per_page'] = $data['per_page'];
        $datas['current_page'] = $data['current_page'];
        $datas['last_page'] = $data['last_page'];
        return $datas;
    }

    
    /**
     * 数据循环增加 序号
     * @param $data 总数据
     * @param $page 页数
     * @param $limit 限制条数
     */
    public function addSerialNumber($data, $page = 1 , $limit = 10, $key_name = 'key')
    {
        foreach ($data as $key => $val) {
            $data[$key][$key_name] = ($page - 1)*$limit + $key + 1;
        }
        return $data;
    }

    /**
     * 处理数据，把数据放到同一级
     * @param $data
     * @param $oneField  一级的 key
     * @param $towField  二级的 key，需要提到第一级的数据  key为健名  值为别名 
     */
    public function disDataSameLevel($data, $oneField, $towField = [])
    {
        if(!empty($data[$oneField])){
            //一维数组的处理方式
            foreach ($towField as $k => $v) {
                if(is_numeric($k)){
                    $data[$v] =  $data[$oneField][$v];
                }else{
                    $data[$v] =  $data[$oneField][$k];
                }
            }
            unset($data[$oneField]);
        }else{
            //二维数组的处理方式
            foreach ($data as $key => &$val) {
                foreach ($towField as $k => $v) {
                    if (is_numeric($k)) {
                        $data[$key][$v] =  $val[$oneField][$v];
                    } else {
                        $data[$key][$v] =  $val[$oneField][$k];
                    }
                }
                unset($val[$oneField]);
            }
        }


        return $data;
    }












}
